import os
import sys
import configparser
import shutil
import zipfile
import traceback
from datetime import datetime
from git import *
from conf import public

class myconf(configparser.ConfigParser):
    def optionxform(self, optionstr):
        return optionstr

class Git_version(object):
    def __init__(self):
        self.config_file = r'update\tools\config.ini'
        self.Equipment_file = r'update\tools\Equipment.ini'
        self.config = myconf()
        self.Equipment = myconf()
        self.config.read(self.config_file)
        self.Equipment.read(self.Equipment_file)
        self.git_file = self.config.get('service_side','git_file')

    def return_update(self):
        update_file = self.config.get('service_side','updata_file')
        lists = os.listdir(update_file)
        zcell_update_json = {}
        for i in lists:
            zcell_update_json[i] = 1
        print(zcell_update_json)

    def file_judge(self):
        repo_path = self.git_file
        print(repo_path)
        lists = os.listdir(repo_path)
        module_list = self.Equipment.options('Equipment2')
        module_file = []
        module_directory = []
        for item in lists:
            module_file.append(item)
        error_list = [x for x in module_file if x not in module_list]
        if len(error_list) == 0:
            for i in module_file:
                module_directory.append(os.path.join(repo_path, i))
        else:
            print('目录异常，没有对应的ini配置')
            exit(1)
        print(module_directory)
        return module_directory

    def git_data(self):
        module_directory = self.file_judge()
        for file in module_directory:
            module_name = file.split('\\').pop()
            repo_url = public.gitlab_url + module_name + '.git'
            Repo.clone_from(repo_url, file)
        print("success")

    def git_version(self):
        module_directory = self.file_judge()
        update_file = self.config.get('service_side', 'updata_file')
        lists = os.listdir(update_file)
        print(module_directory)
        version_json = {}
        version_list = []
        for file in module_directory:
            module_name2 = ""
            try:
                repo = Repo(file)
                module_name1 = file.split('\\').pop()
                module_name2 = self.Equipment.get('Equipment2', module_name1)
            except:
                print('目录非空，没有git clone过数据')
            tagref = TagReference.list_items(repo)
            other_version_list = []
            version_json = dict()
            version_json["modulename"] = module_name2
            if module_name2 in lists:
                version_json["status"] = 1
            else:
                version_json["status"] = 0
            for i in tagref:
                one_version_json = dict()
                one_version_json["version"] = i.name
                if i.tag is not None:
                    one_version_json["versionname"] = i.tag.message
                if i.commit is not None:
                    one_version_json["message"] = i.commit.message
                    one_version_json["committime"] = datetime.fromtimestamp(i.commit.committed_date).strftime(
                        '%Y-%m-%d %H:%M:%S')
                other_version_list.append(one_version_json)
            repo.close()
            version_json["versions"] = other_version_list
            version_list.append(version_json)
        print(version_list)
        return version_list

    def git_show(self):
        version_list = self.git_version()
        show_list = []
        update_file = self.config.get('service_side', 'updata_file')
        update_list1 = os.listdir(update_file)
        update_list2 = []
        for n in update_list1:
            zcell_name = self.Equipment.get('Equipment1',n)
            update_list2.append(zcell_name)

        for i in version_list:
            show_json = {}
            show_json["modulename"] = i["modulename"]
            new_list = i["versions"].pop()
            show_json["version"] = new_list["version"]
            show_json["versionname"] = new_list["versionname"]
            show_json["committime"] = new_list["committime"]
            if show_json["modulename"] in update_list2:
                show_json["status"] = 1
            else:
                show_json["status"] = 0
            show_list.append(show_json)
        return show_list

    def retrieve_directory(self):
        updata_file = self.config.get('service_side','updata_file')
        lists = os.listdir(updata_file)
        updata_json = {}
        for i in lists:
            print(i)
            updata_json[i] = 1
        print(updata_json)
        return updata_json
    
    def update_git(self, git_json):
        git_file = self.config.get('service_side', 'git_file')
        # git_file = r'E:\pycharms\python3.6\actual\simple\create_up\zcell'
        updata_file = self.config.get('service_side', 'updata_file')
        updata_module_file = os.path.join(updata_file, git_json["module"])
        git_name = self.Equipment.get('Equipment1',git_json["module"])
        try:
            lists = os.listdir(updata_module_file)
            repo_path = ''
            lists2 = []
            for i in lists:
                if i.endswith('zip'):
                    a = os.path.join(updata_module_file, i)
                    repo_path = os.path.join(git_file, git_name)
                    c = os.path.join(git_file, i)
                    print(repo_path)
                    shutil.copy(a, git_file)
                    zf = zipfile.ZipFile(c, 'r')
                    zf.extractall(repo_path)
                    zf.close()
                    os.remove(c)
                else:
                    lists2.append(i)
            print(lists2)
            repo = Repo(repo_path)
            index = repo.index
            index.add(lists2)
            index.commit(git_json["commit_message"])
            remote = repo.remote()
            new_tag = repo.create_tag(git_json["tag_version"], message=git_json["tag_message"])
            remote.push()
            remote.push('--tags')
            shutil.rmtree(updata_module_file)
        # except FileNotFoundError as f:
        #     print("目录不存在: %s" % f)
        except:
            traceback.print_exc()
    
# if __name__ == '__main__':
#     a = Git_version()
#     a.git_show()
#     git_json = {"module":"AS-K41103", "commit_message":"修改dll：AlarmPlugin.dll", "tag_version":"v1.1", "tag_message":"修改dll：AlarmPlugin.dll"}
#     a.update_git(git_json)